package com.yaowk.sfp.file.api;

import com.yaowk.sfp.file.api.exception.FileException;
import com.yaowk.sfp.file.api.model.FileModel;
import org.apache.commons.lang3.ArrayUtils;
import org.springframework.util.DigestUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

/**
 * 文件上传工具类
 *
 * @author 小凯
 **/
public abstract class BaseFileUtils implements IFileUtils {

    public String getExtension(String fileName) {
        int i = fileName.indexOf(".");
        String substring = fileName.substring(i, fileName.length());
        return substring;
    }

    public FileModel buildFileModel(MultipartFile file) {
        byte[] bytes;
        try {
            bytes = file.getBytes();
        } catch (IOException e) {
            e.printStackTrace();
            throw new FileException("文件读取错误");
        }
        if (ArrayUtils.isEmpty(bytes)) {
            throw new FileException("文件不允许为空");
        }
        FileModel fileModel = new FileModel();
        String md5 = DigestUtils.md5DigestAsHex(bytes);
        Long size = file.getSize();
        fileModel.setSize(size);
        fileModel.setMd5(md5);
        fileModel.setType(file.getContentType());
        fileModel.setName(file.getOriginalFilename());
        return fileModel;
    }
}
